package com.wstuo.common.security.service;

import com.wstuo.common.exception.ApplicationException;
import com.wstuo.common.file.csv.*;
import com.wstuo.common.security.dao.ICompanyDAO;
import com.wstuo.common.security.dao.IRoleDAO;
import com.wstuo.common.security.dao.IUserDAO;
import com.wstuo.common.security.dto.CompanyDTO;
import com.wstuo.common.security.dto.OrganizationDTO;
import com.wstuo.common.security.entity.Company;
import com.wstuo.common.security.entity.Role;
import com.wstuo.common.security.entity.User;
import com.wstuo.common.security.utils.AppConfigUtils;
import com.wstuo.common.security.utils.AppContext;
import com.wstuo.common.security.utils.FileEncodeUtils;
import com.wstuo.common.security.utils.LanguageContent;
import com.wstuo.common.util.StringUtils;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 公司信息业务
 * 
 */
public class CompanyService implements ICompanyService {
	
	private static final Logger LOGGER = Logger.getLogger(CompanyService.class );
	@Autowired
	private ICompanyDAO companyDAO;
	@Autowired
	private IUserDAO userDAO;
	@Autowired
	private IRoleDAO roleDAO;
	@Autowired
	private AppContext appctx;
	/**
     * 查询顶级公司信息.
     * @return 公司集合：List<CompanyDTO>
     */
	public List<CompanyDTO> findCompanyATree() {
		List<Company> entities = companyDAO.findATree();
		List<CompanyDTO> dtos = new ArrayList<CompanyDTO>();

		for (Company entity : entities) {
			CompanyDTO dto = new CompanyDTO();
			CompanyDTO.entity2dto(entity, dto);
			dtos.add(dto);
		}

		return dtos;
	}

	/**
     * 查询公司信息.
     * @return 公司信息DTO:CompanyDTO
     */
	@Transactional()
	public CompanyDTO findCompany(Long companyNo) {
		CompanyDTO dto = new CompanyDTO();
		if (companyNo != null && companyNo != 0) {
			Company entity = companyDAO.findCompany(companyNo);
			if (entity != null) {
				CompanyDTO.entity2dto(entity, dto);
				dto.setCompanyName(entity.getOrgName());
				if (entity.getPersonInCharge() != null) {
					dto.setPersonInChargeNo(entity.getPersonInCharge()
							.getUserId());
					dto.setPersonInChargeName(entity.getPersonInCharge()
							.getFullName());
				}
			}
		}
		return dto;
	}

	/**
     * 获取LOGO图片流
     * @param companyNo
     * @return InputStream
     */
	public InputStream getImageStream(Long companyNo) {
		InputStream imageStream = null;
		Company entity = companyDAO.findCompany(companyNo);
		String fileUrl = "";
		if(entity!=null){
			fileUrl = entity.getLogo();
		}
		String filePath = AppConfigUtils.getInstance().getImagePath() + "\\"
				+ fileUrl;
		File file = new File(filePath);
		try {
			imageStream = new FileInputStream(file);
		} catch (Exception e) {
			throw new ApplicationException("ERROR_ATTACHMENT_FAIL_READ\n", e);
		}
		return imageStream;
	}

	/**
     * 保存公司信息.
     * @param dto 公司DTO:OrganizationDTO
     */
	@Transactional()
	public void saveCompany(OrganizationDTO dto) {
		Company com = new Company();
		com.setOrgName(dto.getOrgName());
		com.setOfficeFax(dto.getOfficeFax());
		com.setOfficePhone(dto.getOfficePhone());
		com.setAddress(dto.getAddress());
		com.setEmail(dto.getEmail());
		com.setHomePage(dto.getHomePage());
		com.setLogo(dto.getLogo());
		if (dto.getParentOrgNo() != null) {
			com.setParentOrg(companyDAO.findById(dto.getParentOrgNo()));
		}
		companyDAO.save(com);
		dto.setOrgNo(com.getOrgNo());
	}

	/**
     * 修改公司信息.
     * @param dto 公司DTO:OrganizationDTO
     */
	@Transactional()
	public void mergeCompany(OrganizationDTO dto) {
		Company com = null;
		boolean flag = false;
		if (dto.getOrgNo() != null && dto.getOrgNo() != 0) {
			com = companyDAO.findById(dto.getOrgNo());
		}
		// mars remove 20110608
		if (com == null) {
			flag = true;
			com = new Company();
		}
		//dto to entity
		dto2entity(com, dto);
		if (flag) {
			companyDAO.save(com);
		} else {
			companyDAO.merge(com);
		}
		if(com.getParentOrg()!=null){
			com.setPath(com.getParentOrg().getPath()+com.getOrgNo()+"/");
		}else{
			com.setPath(com.getOrgNo()+"/");
		}
		dto.setOrgNo(com.getOrgNo());
		// 将当前用户设置为所属机构
		setUserOrgnization(com);
	}
	
	/**
	 *  将当前用户设置为所属机构
	 * @param com
	 */
	private void setUserOrgnization(Company com){
		boolean onece = true;
		if (companyDAO.findAll() != null && companyDAO.findAll().size() > 0) {
			onece = false;
		}
		if (onece) {// 将当前用户设置为所属机构
			String loginUserName = appctx.getCurrentLoginName();
			User u = userDAO.findUniqueBy("loginName", loginUserName);
			if (u != null) {
				u.setCompanyNo(com.getOrgNo());
				u.setOrgnization(com);
				userDAO.merge(u);
			}
		}
	}
	/**
	 * dto to entity
	 * @param com
	 * @param dto
	 */
	private void dto2entity(Company com ,OrganizationDTO dto){
		com.setOrgName(dto.getOrgName());
		com.setOfficeFax(dto.getOfficeFax());
		com.setOfficePhone(dto.getOfficePhone());
		com.setAddress(dto.getAddress());
		com.setEmail(dto.getEmail());
		com.setHomePage(dto.getHomePage());
		if (StringUtils.hasText(dto.getLogo())) {
			com.setLogo(dto.getLogo());
		}
		com.setSetup(true);
		if (dto.getParentOrgNo() != null) {
			com.setParentOrg(companyDAO.findById(dto.getParentOrgNo()));
		}
		Set<Role> roles = new HashSet<Role>();
		if (dto.getOrgRole() != null) {
			for (Long id : dto.getOrgRole()) {
				Role role = roleDAO.findById(id);
				roles.add(role);
			}
		}
		com.setOrgRoles(roles);
		// 关联负责
		if (dto.getPersonInChargeName() != null) {
			com.setPersonInCharge(userDAO.findUniqueBy("fullName",
					dto.getPersonInChargeName()));
		}
		// 公司负责人
		if (dto.getPersonInChargeNo() != null) {
			com.setPersonInCharge(userDAO.findById(dto.getPersonInChargeNo()));
		}
	}

	/**
     * 根据ID删除公司信息.
     * @param orgNo 公司ID：Long orgNo
     */
	@Transactional()
	public void deleteCompany(Long orgNo) {
		companyDAO.delete(companyDAO.findById(orgNo));
	}

	/**
     * 根据ID查找公司信息.
     * @param id 公司编号：Long id
     * @return Company
     */
	public Company findCompanyById(Long id) {
		return companyDAO.findById(id);
	}

	/**
     * 根据编号查找机构DTO.
     * @param id 机构编号：Long id
     * @return OrganizationDTO
     */
	public OrganizationDTO findById(Long id) {
		OrganizationDTO dto = new OrganizationDTO();
		Company entity = companyDAO.findById(id);
		if (entity != null) {
			OrganizationDTO.entity2dto(entity, dto);
			if (entity.getParentOrg() != null) {
				dto.setParentOrgNo(entity.getParentOrg().getOrgNo());
			}
		}

		return dto;

	}

	/**
     * 导出公司信息.
     * @param paName
     * @param paLogo
     * @return InputStream
     */
	@Transactional
	public InputStream exportCompanyInfo(String paName, String paLogo) {
		LanguageContent lc = LanguageContent.getInstance();
		List<String[]> data = new ArrayList<String[]>();
		data.add(new String[] { lc.getContent("label.sms.orgId"),
				lc.getContent("label.basicSettings.companyName"),
				lc.getContent("label.basicSettings.companyTel"),
				lc.getContent("label.basicSettings.companyFax"),
				lc.getContent("label.basicSettings.companyEmail"),
				lc.getContent("label.basicSettings.companyAddress"),
				lc.getContent("label.basicSettings.companyWebsite"),
				lc.getContent("label.snmp.systemName"),
				lc.getContent("label.basicSettings.companyLOGO"),
				lc.getContent("label.syslogo"),
				lc.getContent("label.report.Logo") });// 加入表头

		Company company = companyDAO.findCompany(0L);
		String imgname = "login_logo.bmp";
		if (paLogo != null && paLogo.length() > 0)
			imgname = paLogo;
		data.add(new String[] { company.getOrgNo() + "", company.getOrgName(),
				" " + company.getOfficePhone() + " ",
				" " + company.getOfficeFax() + " ", company.getEmail(),
				company.getAddress(), company.getHomePage(), paName,
				company.getLogo(), imgname, "logo.jpg" });

		StringWriter sw = new StringWriter();
		CSVWriter csvw = new CSVWriter(sw);
		csvw.writeAll(data);
		ByteArrayInputStream stream = null;

		stream = new ByteArrayInputStream(sw.getBuffer().toString().getBytes());
		try {
        	if(csvw!=null){
        		csvw.flush();
    			csvw.close();
        	}
			if(sw!=null){
				sw.flush();
				sw.close();
			}
		} catch (IOException e) {
			LOGGER.error(e);
		}
		return stream;
	}

	/**
     * 导入公司信息.
     * @param importFile
     * @return import result
     */
	@Transactional
	public String importCompanyInfo(String importFile) {
		String result = "Error";
		Reader rd =null;
		CSVReader reader = null;
		try {
			String fileEncode = FileEncodeUtils.getFileEncode(new File(importFile));
			rd = new InputStreamReader(new FileInputStream(importFile),fileEncode);// 以字节流方式读取数据
			reader = new CSVReader(rd);
			String[] line = null;
			while ((line = reader.readNext()) != null) {
				Company company = new Company();
				if (StringUtils.hasText(line[0])) {
					// 查找公司信息。
					company = companyDAO.findUniqueBy("orgName",
							line[0].toString());
					if (company == null) {
						company = new Company();
						company.setOrgNo(1l);
						company.setLogo("logo.png");
					}
				}
				company.setOrgName(line[0].toString());
				company.setOfficePhone(line[1].toString());
				company.setOfficeFax(line[2].toString());
				company.setEmail(line[3].toString());
				company.setAddress(line[4].toString());
				company.setHomePage(line[5].toString());
				company.setOrgType("company");
				company=companyDAO.merge(company);
				company.setPath(company.getOrgNo()+"/");
				if (line.length > 6) {
					company.setLogo(line[6].toString());
				}
			}
			result = "Success";
		} catch (Exception e) {
			LOGGER.error(e.getMessage());
		} finally {
			try {
				if(rd!=null){
					rd.close();
				}
				if(reader != null){
					reader.close();
				}
			} catch (IOException e) {
				LOGGER.error(e);
			}
		}
		return result;
	}
	/**
     * 根据上传图片名称获取LOGO图片流
     * @param companyNo
     * @return InputStream
     */
	public InputStream getImageUrlforimageStream(String imgFilePath) {
		InputStream imageStream = null;
		String filePath ="";
		if(StringUtils.hasText(imgFilePath)){
			if(imgFilePath.equals("report")){
				filePath = AppConfigUtils.getInstance().getFileManagementPath()+appctx.getCurrentTenantId()+"/jasper/logo.jpg";
			}else{
				filePath = AppConfigUtils.getInstance().getImagePath() + "/"
				+ imgFilePath;
			}
			File file = new File(filePath);
			try {
				imageStream = new FileInputStream(file);
			} catch (Exception e) {
				throw new ApplicationException("ERROR_ATTACHMENT_FAIL_READ\n", e);
			}
		}
		return imageStream;
	}

}
